import store from '../index.js'

// 生成基于用户的购物车存储键
const getCartStorageKey = () => {
  try {
    // 直接从localStorage获取用户信息，避免循环引用
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const { user } = JSON.parse(userInfo)
      if (user && (user.id || user.username)) {
        return `mallCart_${user.id || user.username}`
      }
    }
    // 未登录用户使用默认键
    return 'mallCart_guest'
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return 'mallCart_guest'
  }
}

const loadCartFromStorage = () => {
  try {
    const cartKey = getCartStorageKey()
    const cartData = localStorage.getItem(cartKey)
    return cartData ? JSON.parse(cartData) : []
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    return []
  }
}

// 将购物车数据保存到localStorage
const saveCartToStorage = (cartList) => {
  try {
    const cartKey = getCartStorageKey()
    localStorage.setItem(cartKey, JSON.stringify(cartList))
  } catch (error) {
    console.error('保存购物车数据失败:', error)
  }
}

const state = {
  // 购物车列表，从localStorage初始化
  cartList: loadCartFromStorage()
}

const getters = {
  // 购物车列表
  cartList: state => state.cartList,
  // 获取购物车中商品数量
  getCartNumber: (state) => (productId) => {
    const item = state.cartList.find(item => item.productId === productId)
    return item ? item.quantity : 0
  }
}

const mutations = {
  // 设置购物车列表
  SET_CART_LIST(state, cartList) {
    state.cartList = cartList
    saveCartToStorage(cartList) // 保存到localStorage
  },
  
  // 添加商品到购物车
  ADD_TO_CART(state, product) {
    const existingItem = state.cartList.find(item => item.productId === product.id)
    if (existingItem) {
      existingItem.quantity++
    } else {
      state.cartList.push({
        productId: product.id,
        name: product.name,
        price: product.price,
        image: product.image,
        quantity: 1
      })
    }
    saveCartToStorage(state.cartList) // 保存到localStorage
  },
  
  // 更新购物车商品数量
  UPDATE_CART_ITEM(state, { productId, quantity }) {
    const item = state.cartList.find(item => item.productId === productId)
    if (item) {
      item.quantity = quantity
      saveCartToStorage(state.cartList) // 保存到localStorage
    }
  },
  
  // 从购物车移除商品
  REMOVE_FROM_CART(state, productId) {
    state.cartList = state.cartList.filter(item => item.productId !== productId)
    saveCartToStorage(state.cartList) // 保存到localStorage
  },
  
  // 当用户登录状态改变时，重新加载购物车
  RELOAD_CART(state) {
    state.cartList = loadCartFromStorage()
  }
}

const actions = {
  // 设置购物车列表
  setCartList({ commit }, cartList) {
    commit('SET_CART_LIST', cartList)
  },
  
  // 添加商品到购物车
  addToCart({ commit }, product) {
    commit('ADD_TO_CART', product)
  },
  
  // 更新购物车商品数量
  updateCartItem({ commit }, { productId, quantity }) {
    commit('UPDATE_CART_ITEM', { productId, quantity })
  },
  
  // 从购物车移除商品
  removeFromCart({ commit }, productId) {
    commit('REMOVE_FROM_CART', productId)
  },
  
  // 当用户登录状态改变时调用，重新加载购物车
  onUserStatusChanged({ commit }) {
    commit('RELOAD_CART')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
